<template>
  <div class="app-container">
    <!-- 操作 -->
    <el-row :gutter="20">
      <el-col :span="5">
        <el-button type="danger" icon="el-icon-delete" @click="batchdel()">批量删除</el-button>
      </el-col>
      <el-col :span="9">
        <el-input v-model="query.username" placeholder="请输入账号查找" @keyup.enter.native="searchData()" />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="searchData()">查询</el-button>
        <el-tooltip class="item" effect="dark" content="添加数据" placement="top-start">
          <el-button type="primary" @click="showDialog = true">添加</el-button>
        </el-tooltip>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table :data="tableData" style="width: 100%; margin: 20px 0" stripe border @selection-change="handleSelectionChange" :default-sort="{ prop: 'createTime', order: 'descending' }">
      <el-table-column type="selection" />
      <el-table-column align="center" label="序号" width="60">
        <template slot-scope="scope">
          {{ scope.$index + addIndex }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号" prop="username" />
      <el-table-column align="center" label="密码" prop="password" />
      <el-table-column align="center" label="头像地址" prop="avatar" width="400" />
      <el-table-column align="center" label="邮箱" prop="email" />
      <el-table-column align="center" label="昵称" prop="nickname" />
      <el-table-column align="center" label="创建时间" prop="createTime" sortable />
      <el-table-column align="center" label="更新时间" prop="updateTime" sortable />
      <el-table-column align="center" label="状态" prop="deleted" fixed="right">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.deleted == 0">正常</el-tag>
          <el-tag type="danger" v-else-if="scope.row.deleted == 1">禁用中</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="edit(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.deleted === '0'" size="mini" type="danger" @click="handleDisable(scope.row.id)">禁用</el-button>
          <el-button v-if="scope.row.deleted === '1'" size="mini" type="success" @click="handleEnable(scope.row.id)">启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 页码 -->
    <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange" :total="total" :current-page.sync="query.current" :page-size="query.pageSize" :page-sizes="[10, 20, 30, 40]" background layout="total, sizes, prev, pager, next, jumper" style="text-align: center" />

    <!-- 弹框 -->
    <el-dialog :title="getTitle" :visible.sync="showDialog" :close-on-click-modal="false" @close="closeDialog()" @close-on-press-escape="closeDialog()">
      <el-form ref="userForm" :model="userForm" label-width="120px" :rules="rules">
        <el-form-item label="账号" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="头像地址" prop="avatar">
          <el-input v-model="userForm.avatar" placeholder="请输入头像地址" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="状态" prop="deleted">
          <el-select v-model="userForm.deleted" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="closeDialog()">取消</el-button>
        <el-button v-if="getUserId" type="primary" @click="update('userForm')">更新</el-button>
        <el-button v-else type="primary" @click="save('userForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from '@/api/user'
export default {
  name: 'User',
  data() {
    return {
      query: {
        pageSize: 10,
        current: 1,
        username: '' //查询项
      },
      total: 0,

      // 表格
      tableData: [], // 数据
      addIndex: 1, // 序号
      selectedrow: [], //全选

      // 新增/编辑弹框
      showDialog: false,
      userForm: {
        id: '',
        username: '',
        password: '',
        avatar: '',
        email: '',
        nickname: '',
        deleted: 0
      },
      // 表单验证
      rules: {
        username: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        avatar: [{ required: true, message: '头像地址不能为空', trigger: 'blur' }],
        nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
        deleted: [{ required: true, message: '状态不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    // 弹框标题
    getTitle: function () {
      if (this.userForm.id !== '') {
        return '修改用户信息'
      } else {
        return '添加用户信息'
      }
    },
    // 展示的按钮
    getUserId: function () {
      if (this.userForm.id !== '') {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    this.list()
  },
  methods: {
    // 查询
    searchData() {
      this.query.current = 1
      this.addIndex = this.query.pageSize * (this.query.current - 1) + 1
      this.list()
    },

    // 页码查询
    handleCurrentChange(val) {
      this.query.current = val
      this.addIndex = this.query.pageSize * (this.query.current - 1) + 1
      this.list()
    },

    // 显示条数查询
    handleSizeChange(val) {
      this.query.pageSize = val
      this.query.current = 1
      this.addIndex = this.query.pageSize * (this.query.current - 1) + 1
      this.list()
    },

    // 获取用户列表
    list() {
      userApi.list(this.query).then(response => {
        if (response.code === 20000) {
          let data = response.data.data
          this.tableData = data.records

          this.query.current = data.current
          this.query.pageSize = data.size
          this.total = data.total
        } else {
          this.$message.error(response.message)
        }
      })
    },

    // 禁用用户
    handleDisable(id) {
      this.$confirm('此操作将禁用该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const form = new FormData()
        form.append('id', id)

        userApi.disableUser(form).then(response => {
          if (response.code === 20000) {
            this.$message.success(response.message)
            //刷新页面
            this.list()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },

    // 启用用户
    handleEnable(id) {
      this.$confirm('此操作将启用该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const form = new FormData()
        form.append('id', id)

        userApi.enableUser(form).then(response => {
          if (response.code === 20000) {
            this.$message.success(response.message)
            //刷新页面
            this.list()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },

    // 全选
    handleSelectionChange(val) {
      this.selectedrow = val
    },

    // 批量删除
    batchdel() {
      if (this.selectedrow.length === 0) {
        this.$message('没有任何被选中的数据！')
      } else {
        this.$confirm('此操作将永久删除被选中的用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = []
          for (let i = 0; i < this.selectedrow.length; i++) {
            ids.push(this.selectedrow[i].id)
          }

          const form = new FormData()
          form.append('id', ids.join(','))

          userApi.delByIds(form).then(response => {
            if (response.code === 20000) {
              this.$message.success(response.message)
              //刷新页面
              this.list()
            } else {
              this.$message.error(response.message)
            }
          })
        })
      }
    },

    // 添加用户
    save(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const form = new FormData()
          form.append('id', this.userForm.id)
          form.append('username', this.userForm.username)
          form.append('password', this.userForm.password)
          form.append('avatar', this.userForm.avatar)
          form.append('email', this.userForm.email)
          form.append('nickname', this.userForm.nickname)
          form.append('deleted', Number(this.userForm.deleted))

          userApi.save(form).then(response => {
            if (response.code === 20000) {
              this.$message.success(response.message)
              // 关闭弹框
              this.showDialog = false
              //刷新页面
              this.list()
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },

    // 编辑按钮
    edit(row) {
      this.showDialog = true
      this.userForm.id = row.id
      this.userForm.username = row.username
      this.userForm.password = row.password
      this.userForm.avatar = row.avatar
      this.userForm.email = row.email
      this.userForm.nickname = row.nickname
      this.userForm.deleted = Number(row.deleted)
    },

    // 确认更新用户
    update(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const form = new FormData()
          form.append('id', this.userForm.id)
          form.append('username', this.userForm.username)
          form.append('password', this.userForm.password)
          form.append('avatar', this.userForm.avatar)
          form.append('email', this.userForm.email)
          form.append('nickname', this.userForm.nickname)
          form.append('deleted', Number(this.userForm.deleted))

          userApi.update(form).then(response => {
            if (response.code === 20000) {
              this.$message.success(response.message)
              // 关闭弹框
              this.showDialog = false
              //刷新页面
              this.list()
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },

    // 关闭弹框
    closeDialog() {
      this.showDialog = false
      this.userForm.username = ''
      this.userForm.password = ''
      this.userForm.avatar = ''
      this.userForm.email = ''
      this.userForm.nickname = ''
      this.userForm.deleted = 0
    }
  }
}
</script>
